package org.example.volunteerend.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.example.volunteerend.common.Result;
import org.example.volunteerend.dto.AdminInvitationRequest;
import org.example.volunteerend.dto.AdminProjectReviewRequest;
import org.example.volunteerend.dto.PageResponse;
import org.example.volunteerend.dto.ProjectCategoryRequest;
import org.example.volunteerend.entity.AdminOperationLog;
import org.example.volunteerend.entity.ProjectCategory;
import org.example.volunteerend.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    private final AdminService adminService;
    
    @Autowired
    public AdminController(AdminService adminService) {
        this.adminService = adminService;
    }
    
    /**
     * 生成管理员邀请码
     */
    @PostMapping("/invitation-codes")
    public Result<Map<String, Object>> generateInvitationCode(HttpServletRequest httpRequest) {
        
        // 从JWT获取用户ID进行身份验证
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        //根据用户ID判断是否是管理员


        // 验证用户是否是管理员
        Boolean isAdmin = (Boolean) httpRequest.getAttribute("isAdmin");
        if (isAdmin == null || !isAdmin) {
            return Result.error(403, "权限不足，仅管理员可执行此操作");
        }
        
        try {
            // 创建邀请请求对象，使用JWT中的userId
            AdminInvitationRequest request = new AdminInvitationRequest();
            request.setCreated_by(userId);
            
            Map<String, Object> data = adminService.generateInvitationCode(request);
            
            // 记录操作日志
            adminService.logAdminOperation(
                    userId, 
                    "生成邀请码", 
                    "生成管理员邀请码：" + data.get("invitation_code"), 
                    httpRequest);
            
            return Result.success("邀请码生成成功", data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("邀请码生成失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取管理员操作日志
     */
    @GetMapping("/operation-logs")
    public Result<Map<String, Object>> getOperationLogs(
            HttpServletRequest httpRequest,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) Integer admin_id,
            @RequestParam(required = false) String start_time,
            @RequestParam(required = false) String end_time,
            @RequestParam(required = false) String operation_type) {
        
        // 从JWT获取用户ID进行身份验证
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        // 解析开始时间和结束时间
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        if (start_time != null && !start_time.isEmpty()) {
            try {
                startTime = LocalDateTime.parse(start_time, formatter);
            } catch (Exception e) {
                // 如果格式不匹配，尝试只用日期部分
                try {
                    startTime = LocalDate.parse(start_time).atStartOfDay();
                } catch (Exception ex) {
                    return Result.error("开始时间格式错误，请使用yyyy-MM-dd或yyyy-MM-dd HH:mm:ss格式");
                }
            }
        }
        
        if (end_time != null && !end_time.isEmpty()) {
            try {
                endTime = LocalDateTime.parse(end_time, formatter);
            } catch (Exception e) {
                // 如果格式不匹配，尝试只用日期部分并设置为当天结束
                try {
                    endTime = LocalDate.parse(end_time).plusDays(1).atStartOfDay().minusSeconds(1);
                } catch (Exception ex) {
                    return Result.error("结束时间格式错误，请使用yyyy-MM-dd或yyyy-MM-dd HH:mm:ss格式");
                }
            }
        }
        
        try {
            PageResponse<AdminOperationLog> pageResponse = adminService.getOperationLogs(
                    admin_id, startTime, endTime, operation_type, page, pageSize);
            
            // 转换为符合规范的响应格式
            List<Map<String, Object>> rows = new ArrayList<>();
            for (AdminOperationLog log : pageResponse.getRecords()) {
                Map<String, Object> row = new HashMap<>();
                row.put("log_id", log.getLogId());
                row.put("admin_id", log.getAdminId());
                row.put("admin_name", log.getAdminName());
                row.put("operation_type", log.getOperationType());
                row.put("operation_description", log.getOperationDescription());
                row.put("ip_address", log.getIpAddress());
                row.put("create_time", log.getCreateTime().toString());
                rows.add(row);
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("total", pageResponse.getTotal());
            data.put("rows", rows);
            
            return Result.success(data);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取操作日志失败：" + e.getMessage());
        }
    }
    
    /**
     * 审核项目
     */
    @PutMapping("/projects/{projectId}/review")
    public Result<Map<String, Object>> reviewProject(
            @PathVariable Integer projectId,
            @RequestBody AdminProjectReviewRequest request,
            HttpServletRequest httpRequest) {
        
        // 从JWT获取用户ID进行身份验证
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        try {
            Map<String, Object> data = adminService.reviewProject(projectId, request);
            
            // 记录操作日志
            String operationDescription = "审核项目ID: " + projectId + ", 状态: " + request.getStatus();
            if (request.getComment() != null && !request.getComment().isEmpty()) {
                operationDescription += ", 意见: " + request.getComment();
            }
            
            adminService.logAdminOperation(
                    userId, 
                    "项目审核",
                    operationDescription, 
                    httpRequest);
            
            return Result.success("审核成功", data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("项目审核失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取管理员统计数据
     */
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getStatistics(
            HttpServletRequest httpRequest,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate start_date,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate end_date) {
        
        // 从JWT获取用户ID进行身份验证
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        try {
            Map<String, Object> data = adminService.getStatistics(start_date, end_date);
            
            // 记录操作日志
            adminService.logAdminOperation(
                    userId, 
                    "查看统计数据", 
                    "查看统计数据，时间范围: " + 
                    (start_date != null ? start_date.toString() : "默认") + 
                    " 至 " + 
                    (end_date != null ? end_date.toString() : "今天"), 
                    httpRequest);
            
            return Result.success(data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    /**
     * 添加志愿项目分类
     */
    @PostMapping("/project-categories")
    public Result<ProjectCategory> addProjectCategory(
            @RequestBody ProjectCategoryRequest request,
            HttpServletRequest httpRequest) {
        
        // 从JWT获取用户ID进行身份验证
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        // 验证用户是否是管理员
        Boolean isAdmin = (Boolean) httpRequest.getAttribute("isAdmin");
        if (isAdmin == null || !isAdmin) {
            return Result.error(403, "权限不足，仅管理员可执行此操作");
        }
        
        try {
            // 添加项目分类
            ProjectCategory category = adminService.addProjectCategory(request);
            
            // 记录操作日志
            adminService.logAdminOperation(
                    userId, 
                    "添加项目分类", 
                    "添加项目分类：" + category.getCategoryName(), 
                    httpRequest);
            
            return Result.success("分类添加成功", category);
        } catch (IllegalArgumentException e) {
            if (e.getMessage().contains("分类名称已存在")) {
                return Result.failure(0, e.getMessage());
            }
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加分类失败：" + e.getMessage());
        }
    }

    /**
     * 更新志愿项目分类图标
     */
    @PostMapping("/project-categories/{categoryId}/icon")
    public Result<Map<String, String>> updateCategoryIcon(
            @PathVariable Integer categoryId,
            @RequestParam("icon_file") MultipartFile iconFile,
            HttpServletRequest httpRequest) {
        
        // 从JWT获取用户ID进行身份验证
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        if (userId == null) {
            return Result.error("未登录或登录已过期");
        }
        
        // 验证用户是否是管理员
        Boolean isAdmin = (Boolean) httpRequest.getAttribute("isAdmin");
        if (isAdmin == null || !isAdmin) {
            return Result.error(403, "权限不足，仅管理员可执行此操作");
        }
        
        try {
            // 更新分类图标
            Map<String, String> data = adminService.updateCategoryIcon(categoryId, iconFile);
            
            // 记录操作日志
            adminService.logAdminOperation(
                    userId, 
                    "更新分类图标", 
                    "更新分类ID: " + categoryId + " 的图标", 
                    httpRequest);
            
            return Result.success(data);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新分类图标失败：" + e.getMessage());
        }
    }
} 